<template>
  <div>
    <div class="search-container">
        <!-- 顶部搜索 -->
        <form action="/">
            <van-search
                v-model="searchText"
                class="search-top"
                show-action
                placeholder="请输入搜索关键词"
                background="#3296fa"
                shape="round"
                @search="onSearch"
                @cancel="onCancel"
                @focus="isResultShow = false"
            />
        </form>
        <!-- 搜索结果 -->
        <searchResultVue 
            v-if="isResultShow"
            :search_text="searchText"
        />

        <!-- 联想建议 -->
        <searchSuggestionVue 
            v-else-if="searchText"
            :search_text="searchText"
            @search="onSearch"
        />

        <!-- 搜索历史记录 -->
        <searchHistoryVue v-else
            :searchHistoryText="searchHistoryS"
            @SHistory="searchHistoryS = []"
            @search="onSearch"
        />

    </div>
  </div>
</template>

<script>
import searchHistoryVue from './components/search-history.vue'
import searchSuggestionVue from './components/search-suggestion.vue'
import searchResultVue from './components/search-result.vue'
import { getItem, setItem } from '@/utils/storage'
export default {
    name:'SearchIndex',
    data() {
        return {
            searchText: '',
            isResultShow: false, //控制搜索结果显示
            searchHistoryS: getItem('TOUTIAO_SEARCH_HISTORYS') || [], //搜索记录

        };
    },
    methods: {
        onSearch(val) {
            //更新文本框内容
            this.searchText = val

            //存储搜索结果
            /*
                要求：无重复记录，最新搜索排在最前面
            */
           const index = this.searchHistoryS.indexOf(val)
           if(index !== -1){
            this.searchHistoryS.splice(index,1)
           }
            this.searchHistoryS.unshift(val)

            //显示搜索结果
            this.isResultShow = true
        },
        onCancel() {
            this.$router.back()
        },
    },
    components:{
        searchHistoryVue,
        searchSuggestionVue,
        searchResultVue
    },
    watch:{
        deep:true,
        searchHistoryS(val){
            setItem('TOUTIAO_SEARCH_HISTORYS',val)
        }
    }

}
</script>
<style lang="less" scoped>
    .search-container{
        padding-top: 108px;
        .van-search__action{
            color: aliceblue;
        }
        .search-top{
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            z-index: 1;
        }
    }
</style>